
import codecs

class FileRead:
    ''' read big text file as iterator
    '''
    def __init__(self , flpath):
        self.flpath = flpath
        # 2010-09-30_2017 vp, do not assume newline characters
        #self.sfile = open(flpath, 'r') 
        self.sfile = open(flpath, 'rb') 
        
    def __getitem__( self , index ):
        line = self.sfile.readline()
        if line:
            return line
        else:
            raise IndexError

class lines:
    ''' read big text file as iterator
    '''
    def __init__(self , fpath, encoding=''):
        self.file_path = fpath
        # be able to define (to avoid guessing) input encoding 
        self.file_encoding = encoding
        
        #self.file_handle = open(fpath, 'r')
        #self.file_handle = open(fpath, 'U')
        # 2010-09-30_2017 vp, do not assume newline characters, read in binary mode
        if   self.file_encoding == 'utf-8':
            self.file_handle = codecs.open(self.file_path, 'rb', 'utf-8')
        elif self.file_encoding in ('win1250', 'cp1250'):
            self.file_handle = codecs.open(self.file_path, 'rb', 'cp1250')
        else:
            self.file_handle = open(self.file_path, 'rb')


    def __getitem__( self , index ):
        line = self.file_handle.readline()
        if line:
            return line
        else:
            raise IndexError

class lines2:
    ''' rewrite of "lines" class
    '''
    def __init__(self,fpath):
        self.fpath = fpath
        # 2010-09-30_2017 vp, do not assume newline characters
        #self.fhandle = open(self.fpath, 'r')
        self.fhandle = open(self.fpath, 'rb')

    def __getitem__(self):
        line = self.fhandle.readline()
        if line:
            return line
        else:
            raise IndexError

    def getLine(self):
        return self.__getitem__()


def lineno(inpFile, lineNo):
    if lineNo < 1 : return ''
    inpLineNo = 0
    # 2010-09-30_2017 vp, do not assume newline characters
    #inpFileObj = open(inpFile, 'r')
    inpFileObj = open(inpFile, 'rb')
    
    while 1:
        if inpLineNo <> lineNo:
            inpLineNo += 1
            inpLine = inpFileObj.readline()
        else:
            inpFileObj.close()
            return inpLine

